/*
 * @Author: zhangyujie
 * @Date:   2015-08-12 10:43:00
 * @Last Modified by:   zhangyujie
 * @Last Modified time: 2015-08-14 16:16:45
 */

'use strict';

(function() {

	var Y = window.Y || {}

	var util = {

		getNumByRate: function(w, rate) {

			if (typeof rate === 'string' && rate.indexOf('%')) {

				return w * Number(rate.replace('%', '')) / 100
			} else if (typeof rate === 'string' && rate.indexOf('px')) {

				return Number(rate.replace('px', ''))
			} else {

				return Number(rate)
			}
		},
		getTextSize: function(text, style) {

			var span, position, width, height

			span = document.createElement('span')

			span.innerText = text

			for (var key in style) {

				span.style[key] = style[key]
			}

			document.body.appendChild(span)

			position = span.getBoundingClientRect()

			width = position.width

			height = position.height

			document.body.removeChild(span)

			return {

				width: width,
				height: height
			}
		}
	}

	Y.four = function(setting) {

		var selector = setting.selector,
			series = setting.series,
			dataset = series.dataset,
			otherColor = setting.otherColor,
			colorset = setting.colorset,
			xSetting = setting.xAxis,
			ySetting = setting.yAxis,
			radius = setting.radius,
			margin = setting.margin,
			width = document.querySelector(selector).offsetWidth,
			height = document.querySelector(selector).offsetHeight,
			length = dataset.length,
			dom = document.querySelector(selector),
			contentW = width - margin.left - margin.right,
			contentH = height - margin.top - margin.bottom

		var svg,
			content,
			totalGroup,
			xScale,
			yScale,
			incomeGroup,
			circle,
			xAxis,
			yAxis,
			xAxisData = [],
			yAxisData = [],
			yMax,
			diff

		for (var i = 0, tempData; tempData = dataset[i++];) {
			xAxisData.push(tempData['name'])
		}
		yMax = d3.max(dataset, function(d, i) {
			return d['value']
		})

		diff = yMax / 10
		for (var i = 0; i < yMax; i += diff) {
			yAxisData.push(Number(i.toFixed(1)))
		}
		yAxisData.push(yMax)

		xScale = d3.scale.ordinal()
			.domain(xAxisData)
			// .rangeRoundPoints([margin.left, width - margin.right])
			.rangeRoundPoints([0, contentW])


		yScale = d3.scale.linear()
			.domain([0, yMax])
			//.range([height - margin.bottom, margin.top])
			.range([contentH, 0])

		svg = d3.select(selector).append('svg')
			.attr('width', width)
			.attr('height', height)

		content = svg.append('g')
			.attr('class', 'content')
			.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')

		xAxis = d3.svg.axis()
			.scale(xScale)
			.tickValues(xAxisData)
			.tickPadding(xSetting.tickPadding)
			.orient('bottom')
			.tickSize(0)
		yAxis = d3.svg.axis()
			.scale(yScale)
			.tickValues(yAxisData)
			.orient('right')
			.tickSize(0)

		content.append('rect')
			.attr('x', 0)
			.attr('y', 0)
			.attr('fill', '#E3E3E3')
			.attr('width', xSetting['rect']['width'])
			.attr('height', xSetting['rect']['height'])
			.attr('transform', 'translate(' + (-margin.left) + ',' + (contentH) + ')')
		content.append('g')
			.attr('class', 'xAxis')
			.attr('transform', 'translate(' + 0 + ',' + (contentH) + ')')
			.call(xAxis)
		content.append('g')
			.attr('class', 'yAxis')
			.attr('transform', 'translate(' + contentW + ',' + 0 + ')')
			.call(yAxis)



		content.select('.yAxis .tick text')
			.remove()

		svg.selectAll('.xAxis .tick')
			.append('line')
			.attr('x1', 0)
			.attr('y1', 0)
			.attr('x2', 0)
			.attr('y2', -(contentH))
		svg.selectAll('.yAxis .tick')
			.attr('opacity', function(d, i) {
				if (i == yAxisData.length - 1) {
					d3.select(this).append('line')
						.attr('x1', 0)
						.attr('y1', 0)
						.attr('x2', -(width - margin.left - margin.right))
						.attr('y2', 0)

				}
			})

		var brokeLinear = content.append('defs')
			.append('linearGradient')
			.attr('id', 'brokeArea')
			.attr('x1', '100%')
			.attr('y1', '100%')
			.attr('x2', '100%')
			.attr('y2', '0%')

		svg.append("clipPath")
			.attr("id", "content-brokeArea")
			.append("rect")
			.attr("x", -10)
			.attr("y", -10)
			.attr("height", height)
			.attr("width", "10")
			.transition()
			.duration(1000)
			.attr("width", width);

		brokeLinear.append('stop')
			.attr('offset', '0%')
			.style({
				'stop-color': '#DDEDFD',
				'stop-opacity': 0.5
			})

		brokeLinear.append('stop')
			.attr('offset', '25%')
			.style({
				'stop-color': '#84C6FF',
				'stop-opacity': 1
			})
		var area = d3.svg.area()
			.x(function(d, i) {
				return xScale(xAxisData[i])
			})
			.y0(height - margin.bottom)
			.y1(function(d, i) {

				return yScale(d['value'])
			});
		var brokeArea = content.append('g')
			.attr('class', 'brokeArea')
			.attr("clip-path", "url(#content-brokeArea)")
		var pct = brokeArea.append("g")
			.attr("class", "pct")


		pct.append("path")
			.datum(dataset)
			.attr("fill", 'url(#brokeArea)')
			.attr("d", area)
			.style("opacity", "0.7")

		brokeArea.selectAll('.circle')
			.data(dataset)
			.enter()
			.append('circle')
			.attr('class', '.circle')
			.attr('r', radius)
			.attr('cx', function(d, i) {
				return xScale(xAxisData[i])
			})
			.attr('cy', function(d, i) {
				return yScale(d['value'])
			})
			.attr('fill', '#fff')
			.attr('stroke', '#84C6FF')
			.attr('stroke-width', 1)



		var lineWrap = content.append('g')
			.style('display', 'none')
		var line = lineWrap
			.append('line')
			.attr('x1', 0)
			.attr('y2', 0)
			.attr('x2', 0)
			.attr('y2', contentH)
			.attr('fill', '#84C6FF')
			.attr('stroke', '#84C6FF')
		var circleWrap = lineWrap
			.append('g')

		circleWrap.append('circle')
			.attr('r', 10)
			.attr('fill', '#fff')
			.attr('stroke-width', '2px')
			.attr('stroke', '#84C6FF')

		circleWrap.append('circle')
			.attr('r', 6)
			.attr('fill', '#84C6FF')

		content
			.on('touchstart', touch)
			.on('touchmove', touch)


		function touch() {

			var tagName, height,
				position, left, key,
				lineValue, rectValue,
				index, arr

			position = d3.mouse(dom)

			left = position[0] - margin.left

			if (left >= 0 && left <= contentW) {

				arr = getData(left)

				lineWrap.style('display', 'block')

				line
					.attr('transform', 'translate(' + left + ',' + 0 + ')')

				circleWrap
					.attr('transform', 'translate(' + left + ',' + arr[1] + ')')
			}

		}

		function getData(num) {

			var unitData = contentW / (xAxisData.length - 1),
				preIndex,
				nextIndex, currentIndex, k,
				vaildIndex, y, currentValue, vaildValue, x, b


			var currentIndex = Math.floor(num / unitData)

			if (currentIndex < 0) {

				currentIndex = 0
			}

			if (currentIndex > xAxisData.length - 1) {

				currentIndex = xAxisData.length - 1
			}


			vaildIndex = Math.min(currentIndex + 1, xAxisData.length - 1)



			currentValue = yScale(dataset[currentIndex].value)

			vaildValue = yScale(dataset[vaildIndex].value)

			x = num - (currentIndex * unitData)

			k = 1

			b = currentValue

			y = k * (vaildValue - currentValue) * x / unitData + b

			return [currentIndex, y]
		}



	}

	window.Y = Y

}())